<template>
  <div>
    <el-container>
      <el-header>
        广告列表
      </el-header>
      <el-main>
        <el-card>
          <el-form :model="content" class="content-form">
            <el-form-item label="标题">
              <el-input
                  v-model="content.title"
                  placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="类别">
              <el-select
                  v-model="content.categoryId"
                  placeholder="全部类别"
                  style="width: 120px">
                <el-option label="全部类别" value="0" />
                <el-option
                    v-for="(item, index) in contentCategory"
                    :key="index"
                    :label="item.name"
                    :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                  plain
                  type="primary"
                  @click="searchContent">
                搜索
              </el-button>
              <el-button
                  plain
                  @click="
									;(dialogFormVisible = true),
										(dialogTitle = '添加广告'),
										(contentInfo = {})
								">
                添加
              </el-button>
              <el-button plain @click="toggleSelection()">
                删除
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
              :data="tableData"
              class="content-list"
              style="width: 100%"
              @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="广告id" prop="id" />
            <el-table-column label="标题" prop="title" />
            <el-table-column label="路径" prop="url" />
            <el-table-column label="图片" prop="pic" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                    size="small"
                    @click="
										handleEdit(scope.$index, scope.row)
									">
                  编辑
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    @click="
										handleDetele(scope.$index, scope.row)
									">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :background="background"
              :disabled="disabled"
              :page-sizes="[2, 3, 5, 7]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
        </el-card>
        <el-dialog
            v-model="dialogFormVisible"
            :title="dialogTitle"
            width="500">
          <el-form :rules="rules" :model="contentInfo">
            <el-form-item
                :label-width="formLabelWidth"
                label="编号">
              <el-input
                  v-model="contentInfo.id"
                  autocomplete="off"
                  disabled />
            </el-form-item>
            <el-form-item
                :label-width="formLabelWidth"
                prop="title"
                label="标题">
              <el-input
                  v-model="contentInfo.title"
                  autocomplete="off" />
            </el-form-item>
            <el-form-item
                :label-width="formLabelWidth"
                prop="url"
                label="路径">
              <el-input
                  v-model="contentInfo.url"
                  autocomplete="off" />
            </el-form-item>
            <el-form-item
                :label-width="formLabelWidth"
                prop="pic"
                label="图片">
              <el-upload
                  class="upload-demo"
                  action=""
                  :http-request="uploadFile"
                  :before-upload="beforeUpload"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="类别">
              <el-select
                  v-model="content.categoryId"
                  placeholder="全部类别"
                  style="width: 120px">
                <el-option label="全部类别" value="0" />
                <el-option
                    v-for="(item, index) in contentCategory"
                    :key="index"
                    :label="item.name"
                    :value="item.id" />
              </el-select>
            </el-form-item>
          </el-form>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="formSubmitHandler">
            确定
          </el-button>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import contentApi from '../http/httpContentRequest.js'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import axios from 'axios'
const formLabelWidth = ref('100px')
const tableData = ref([])


const pageSize = ref(3)
const pageNum = ref(1)
const total = ref(20)
const background = ref(false)
const disabled = ref(false)


const handleCurrentChange = (num) => {
  pageNum.value = num
  searchContent()
}
const handleSizeChange = (size) => {
  pageSize.value = size

  searchContent()
}

const content = ref({})
const searchContent = async () => {
  const searchUrl = `/content/search/${pageNum.value}/${pageSize.value}`;
  const result = await contentApi.doPost(searchUrl, content.value);
  tableData.value = result.data.pr.rows
  total.value = result.data.pr.total
}


const contentCategory = ref([])
const contentCategoryList = async () => {
  let result = await contentApi.doGet("/contentCategory/list")
  contentCategory.value = result.data.list
}
contentCategoryList()

const contentInfo = ref({})
const dialogFormVisible = ref(false)
const dialogTitle = ref('添加广告')

const handleEdit = (index, row) => {
  dialogFormVisible.value = true
  dialogTitle.value = '编辑广告'
  contentInfo.value.title = row.title
  contentInfo.value.url = row.url
  contentInfo.value.pic = row.pic
  contentInfo.value.categoryId = row.categoryId

}


const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const handleDetele = async (index,row) => {
  this.ids = []
  if(row){
    this.ids.push(row.id)
  }else{
    this.ids = multipleSelection.value.map((row) => row.id).join(',')
  }
  contentApi.doDelete(`/content/delete/${ids}`).then( (resp) => {
    if (resp.code === 200) {
      this.$message({
        type: 'success',
        message: resp.message,
        onClose: () => {

          searchContent()
        }
      })
    } else {
      this.$message({
        type: 'error',
        message: res.message
      })
    }
  })

}

const formSubmitHandler = () => {
  let result
  ElMessageBox.confirm(`确认${dialogTitle.value}吗`)
      .then(async () => {
        if (dialogTitle.value === '添加广告') {

          result = await contentApi.doPost("/content/add",contentInfo.value);
        }
        if (dialogTitle.value === '编辑广告') {
          contentInfo.value.pic=  dialogImagePic.value;
          result = await contentApi.doPost("/content/update",contentInfo.value)
        }
        console.log(result)
        ElNotification({
          message: result.message,
          type: result.code === 200 ? 'success' : 'error',
        })
        await searchContent()
      })
      .catch(() => {
        ElMessage.info('取消')
      })

  dialogFormVisible.value = false
}
const dialogImagePic = ref('');
const dialogVisible = ref(false);

const uploadFile = async ({ file, onProgress, onSuccess, onError }) => {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await axios.post('/hzit/content/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: progressEvent => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress({ percent: percentCompleted }, file);
      }
    });

    onSuccess(response.data);
    dialogImagePic.value = response.data.pic;
    dialogVisible.value = true;
  } catch (error) {
    onError(error);
  }
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    this.$message.error('上传文件只能是图片!');
  }
  if (!isLt2M) {
    this.$message.error('上传图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};

const handlePictureCardPreview = (file) => {
  dialogImagePic.value = file.pic;
  dialogVisible.value = true;
};

const rules = {
  title: [
    {
      required: true,
      message: '标题',
      trigger: 'blur',
    },
    {
      min: 5,
      max: 16,
      message: '5-16位非空字符',
      trigger: 'blur',
    },
  ],
  url: [
    {
      required: true,
      message: 'url',
      trigger: 'blur',
    },
  ],
  categoryId: [
    {
      required: true,
      message: '请选择广告类别',
      trigger: 'blur',
    },
  ],
}
</script>

<style scoped>
.content-list {
  text-align: center;
}

.content-form {
  display: flex;
  text-align: center;
  justify-content: space-around;
}
</style>
